<template>
  <div class="execution-monitor">
    <div class="page-header">
      <h2>执行监控</h2>
      <div class="header-actions">
        <el-button @click="refreshData" :icon="Refresh">刷新</el-button>
        <el-button type="primary" @click="executeFlow" :icon="VideoPlay">执行流程</el-button>
      </div>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon running">
                <el-icon><Timer /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ stats.running }}</div>
                <div class="stats-label">运行中</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon success">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ stats.success }}</div>
                <div class="stats-label">成功</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon failed">
                <el-icon><CircleClose /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ stats.failed }}</div>
                <div class="stats-label">失败</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon total">
                <el-icon><DataAnalysis /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-value">{{ stats.total }}</div>
                <div class="stats-label">总计</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 搜索筛选 -->
    <div class="search-section">
      <el-form :model="searchForm" inline>
        <el-form-item label="执行ID">
          <el-input v-model="searchForm.executionId" placeholder="请输入执行ID" clearable></el-input>
        </el-form-item>
        <el-form-item label="流程编码">
          <el-input v-model="searchForm.flowCode" placeholder="请输入流程编码" clearable></el-input>
        </el-form-item>
        <el-form-item label="执行状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="运行中" value="RUNNING"></el-option>
            <el-option label="成功" value="SUCCESS"></el-option>
            <el-option label="失败" value="FAILED"></el-option>
            <el-option label="已停止" value="STOPPED"></el-option>
            <el-option label="暂停" value="PAUSED"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="执行时间">
          <el-date-picker
            v-model="searchForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchExecutions" :icon="Search">搜索</el-button>
          <el-button @click="resetSearch" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 执行记录列表 -->
    <div class="table-section">
      <el-table 
        :data="executionList" 
        v-loading="loading"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="executionId" label="执行ID" width="200"></el-table-column>
        <el-table-column prop="flowCode" label="流程编码" width="150"></el-table-column>
        <el-table-column prop="flowName" label="流程名称" width="200"></el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" :icon="getStatusIcon(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180"></el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180"></el-table-column>
        <el-table-column prop="duration" label="执行时长" width="120">
          <template #default="{ row }">
            <span v-if="row.duration">{{ formatDuration(row.duration) }}</span>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="进度" width="120">
          <template #default="{ row }">
            <el-progress 
              :percentage="row.progress" 
              :status="row.status === 'FAILED' ? 'exception' : ''"
              :stroke-width="8"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons-container">
              <el-button type="primary" size="small" @click="viewDetails(row)" :icon="View">详情</el-button>
              <el-button type="primary" size="small" @click="viewLogs(row)" :icon="Document">日志</el-button>
              <el-button 
                v-if="row.status === 'RUNNING'"
                size="small" 
                type="warning"
                @click="stopExecution(row)"
                :icon="VideoPause"
              >
                停止
              </el-button>
              <el-button 
                v-if="row.status === 'PAUSED'"
                size="small" 
                type="success"
                @click="resumeExecution(row)"
                :icon="VideoPlay"
              >
                恢复
              </el-button>
              <el-button 
                v-if="['FAILED', 'STOPPED'].includes(row.status)"
                size="small" 
                type="success"
                @click="retryExecution(row)"
                :icon="RefreshRight"
              >
                重试
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 执行详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="执行详情"
      width="1000px"
    >
      <div class="detail-content" v-if="currentExecution">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="执行ID">{{ currentExecution.executionId }}</el-descriptions-item>
          <el-descriptions-item label="流程编码">{{ currentExecution.flowCode }}</el-descriptions-item>
          <el-descriptions-item label="流程名称">{{ currentExecution.flowName }}</el-descriptions-item>
          <el-descriptions-item label="执行状态">
            <el-tag :type="getStatusType(currentExecution.status)">
              {{ getStatusLabel(currentExecution.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ currentExecution.startTime }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ currentExecution.endTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="执行时长">
            {{ currentExecution.duration ? formatDuration(currentExecution.duration) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="链路追踪ID">{{ currentExecution.traceId }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="execution-flow" v-if="executionNodes.length > 0">
          <h4>节点执行情况</h4>
          <el-timeline>
            <el-timeline-item
              v-for="node in executionNodes"
              :key="node.nodeId"
              :type="getNodeStatusType(node.status)"
              :icon="getNodeStatusIcon(node.status)"
              :timestamp="node.startTime"
            >
              <div class="node-info">
                <div class="node-header">
                  <span class="node-name">{{ node.nodeName }}</span>
                  <el-tag size="small" :type="getNodeStatusType(node.status)">
                    {{ getNodeStatusLabel(node.status) }}
                  </el-tag>
                </div>
                <div class="node-details">
                  <p><strong>节点编码：</strong>{{ node.nodeCode }}</p>
                  <p><strong>执行时长：</strong>{{ node.duration ? formatDuration(node.duration) : '-' }}</p>
                  <p v-if="node.errorMessage"><strong>错误信息：</strong>{{ node.errorMessage }}</p>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 执行日志对话框 -->
    <el-dialog 
      v-model="logDialogVisible" 
      title="执行日志"
      width="800px"
    >
      <div class="log-content">
        <div class="log-toolbar">
          <el-button size="small" @click="refreshLogs" :icon="Refresh">刷新</el-button>
          <el-button size="small" @click="clearLogs" :icon="Delete">清空</el-button>
          <el-switch
            v-model="autoRefreshLogs"
            active-text="自动刷新"
            inactive-text="手动刷新"
          />
        </div>
        <div class="log-viewer" ref="logViewer">
          <pre v-for="(log, index) in executionLogs" :key="index" :class="getLogClass(log.level)">{{ formatLogEntry(log) }}</pre>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="logDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 执行流程对话框 -->
    <el-dialog 
      v-model="executeDialogVisible" 
      title="执行流程"
      width="600px"
    >
      <el-form :model="executeForm" label-width="100px">
        <el-form-item label="流程编码" required>
          <el-select v-model="executeForm.flowCode" placeholder="请选择流程" style="width: 100%">
            <el-option 
              v-for="flow in availableFlows"
              :key="flow.flowCode"
              :label="`${flow.flowName} (${flow.flowCode})`"
              :value="flow.flowCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="执行模式">
          <el-radio-group v-model="executeForm.async">
            <el-radio :label="false">同步执行</el-radio>
            <el-radio :label="true">异步执行</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="输入参数">
          <el-input 
            v-model="executeForm.inputData" 
            type="textarea" 
            :rows="6"
            placeholder="请输入执行参数（JSON格式）"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="executeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitExecution" :loading="executing">
            {{ executing ? '执行中...' : '开始执行' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Refresh, VideoPlay, Search, View, Document, VideoPause, 
  RefreshRight, Delete, Timer, CircleCheck, CircleClose, 
  DataAnalysis 
} from '@element-plus/icons-vue'
import {
  getExecutionPage,
  executeFlowSync,
  executeFlowAsync,
  getExecutionById,
  stopExecution as stopExecutionApi,
  retryExecution as retryExecutionApi,
  pauseExecution,
  resumeExecution as resumeExecutionApi,
  getRunningExecutions,
  getExecutionNodes
} from '@/api/execution'
import { getAllEnabledFlows } from '@/api/flow'

// 响应式数据
const loading = ref(false)
const executing = ref(false)
const detailDialogVisible = ref(false)
const logDialogVisible = ref(false)
const executeDialogVisible = ref(false)
const autoRefreshLogs = ref(false)
const logViewer = ref(null)

// 定时器
let refreshTimer = null
let logRefreshTimer = null

// 统计数据
const stats = reactive({
  running: 0,
  success: 0,
  failed: 0,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  executionId: '',
  flowCode: '',
  status: '',
  timeRange: []
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 执行记录列表
const executionList = ref([])

// 当前查看的执行记录
const currentExecution = ref(null)
const executionNodes = ref([])
const executionLogs = ref([])

// 可用流程列表
const availableFlows = ref([])

// 执行表单
const executeForm = reactive({
  flowCode: '',
  async: true,
  inputData: '{\n  "param1": "value1",\n  "param2": "value2"\n}'
})

/**
 * 获取状态标签
 */
const getStatusLabel = (status) => {
  const labels = {
    RUNNING: '运行中',
    SUCCESS: '成功',
    FAILED: '失败',
    STOPPED: '已停止',
    PAUSED: '暂停'
  }
  return labels[status] || status
}

/**
 * 获取状态类型
 */
const getStatusType = (status) => {
  const types = {
    RUNNING: 'primary',
    SUCCESS: 'success',
    FAILED: 'danger',
    STOPPED: 'warning',
    PAUSED: 'info'
  }
  return types[status] || ''
}

/**
 * 获取状态图标
 */
const getStatusIcon = (status) => {
  const icons = {
    RUNNING: Timer,
    SUCCESS: CircleCheck,
    FAILED: CircleClose,
    STOPPED: VideoPause,
    PAUSED: VideoPause
  }
  return icons[status] || Timer
}

/**
 * 获取节点状态标签
 */
const getNodeStatusLabel = (status) => {
  const labels = {
    PENDING: '等待中',
    RUNNING: '运行中',
    SUCCESS: '成功',
    FAILED: '失败',
    SKIPPED: '跳过'
  }
  return labels[status] || status
}

/**
 * 获取节点状态类型
 */
const getNodeStatusType = (status) => {
  const types = {
    PENDING: 'info',
    RUNNING: 'primary',
    SUCCESS: 'success',
    FAILED: 'danger',
    SKIPPED: 'warning'
  }
  return types[status] || ''
}

/**
 * 获取节点状态图标
 */
const getNodeStatusIcon = (status) => {
  const icons = {
    PENDING: 'Clock',
    RUNNING: 'Loading',
    SUCCESS: 'Check',
    FAILED: 'Close',
    SKIPPED: 'Minus'
  }
  return icons[status] || 'Clock'
}

/**
 * 格式化时长
 */
const formatDuration = (duration) => {
  if (duration < 1000) {
    return `${duration}ms`
  } else if (duration < 60000) {
    return `${(duration / 1000).toFixed(1)}s`
  } else {
    const minutes = Math.floor(duration / 60000)
    const seconds = Math.floor((duration % 60000) / 1000)
    return `${minutes}m ${seconds}s`
  }
}

/**
 * 获取日志样式类
 */
const getLogClass = (level) => {
  return `log-${level.toLowerCase()}`
}

/**
 * 格式化日志条目
 */
const formatLogEntry = (log) => {
  return `[${log.timestamp}] [${log.level}] ${log.message}`
}

/**
 * 加载统计数据
 */
const loadStats = async () => {
  try {
    // 获取运行中的执行记录
    const runningResponse = await getRunningExecutions()
    stats.running = runningResponse.data?.length || 0
    
    // 获取总体统计数据（通过分页查询获取）
    const allResponse = await getExecutionPage({
      current: 1,
      size: 1000 // 获取足够多的数据用于统计
    })
    
    if (allResponse.data?.records) {
      const records = allResponse.data.records
      stats.total = allResponse.data.total || records.length
      stats.success = records.filter(r => r.status === 'SUCCESS').length
      stats.failed = records.filter(r => r.status === 'FAILED').length
    }
    
  } catch (error) {
    console.error('加载统计数据失败：', error)
    // 使用模拟数据作为降级
    Object.assign(stats, {
      running: 5,
      success: 128,
      failed: 12,
      total: 145
    })
  }
}

/**
 * 加载执行记录列表
 */
const loadExecutionList = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      current: pagination.current,
      size: pagination.size
    }
    
    // 添加搜索条件
    if (searchForm.executionId) {
      params.executionId = searchForm.executionId
    }
    if (searchForm.flowCode) {
      params.flowCode = searchForm.flowCode
    }
    if (searchForm.status) {
      params.status = searchForm.status
    }
    if (searchForm.timeRange && searchForm.timeRange.length === 2) {
      params.startTime = searchForm.timeRange[0]
      params.endTime = searchForm.timeRange[1]
    }
    
    const response = await getExecutionPage(params)
    
    if (response.data) {
      executionList.value = response.data.records || []
      pagination.total = response.data.total || 0
    }
    
  } catch (error) {
    ElMessage.error('加载执行记录失败：' + error.message)
    // 使用模拟数据作为降级
    executionList.value = [
      {
        id: 1,
        executionId: 'exec_20240101_001',
        flowCode: 'user_register_flow',
        flowName: '用户注册流程',
        status: 'RUNNING',
        startTime: '2024-01-01 10:00:00',
        endTime: null,
        duration: null,
        progress: 60,
        traceId: 'trace_001'
      }
    ]
    pagination.total = 1
  } finally {
    loading.value = false
  }
}

/**
 * 加载可用流程列表
 */
const loadAvailableFlows = async () => {
  try {
    const response = await getAllEnabledFlows()
    
    if (response.data) {
      availableFlows.value = response.data.map(flow => ({
        flowCode: flow.flowCode,
        flowName: flow.flowName
      }))
    }
    
  } catch (error) {
    console.error('加载可用流程失败：', error)
    // 使用模拟数据作为降级
    availableFlows.value = [
      { flowCode: 'user_register_flow', flowName: '用户注册流程' },
      { flowCode: 'data_sync_flow', flowName: '数据同步流程' },
      { flowCode: 'order_process_flow', flowName: '订单处理流程' }
    ]
  }
}

/**
 * 刷新数据
 */
const refreshData = () => {
  loadStats()
  loadExecutionList()
}

/**
 * 搜索执行记录
 */
const searchExecutions = () => {
  pagination.current = 1
  loadExecutionList()
}

/**
 * 重置搜索
 */
const resetSearch = () => {
  Object.assign(searchForm, {
    executionId: '',
    flowCode: '',
    status: '',
    timeRange: []
  })
  searchExecutions()
}

/**
 * 分页大小变化
 */
const handleSizeChange = (size) => {
  pagination.size = size
  loadExecutionList()
}

/**
 * 当前页变化
 */
const handleCurrentChange = (current) => {
  pagination.current = current
  loadExecutionList()
}

/**
 * 查看详情
 */
const viewDetails = async (row) => {
  currentExecution.value = row
  
  try {
    // 加载节点执行情况
    const response = await getExecutionNodes(row.id)
    
    if (response.data) {
      executionNodes.value = response.data
    }
  } catch (error) {
    console.error('加载节点执行情况失败：', error)
    // 使用模拟数据作为降级
    executionNodes.value = [
      {
        nodeId: 'node_001',
        nodeCode: 'start_node',
        nodeName: '开始节点',
        status: 'SUCCESS',
        startTime: '2024-01-01 10:00:00',
        endTime: '2024-01-01 10:00:01',
        duration: 1000
      },
      {
        nodeId: 'node_002',
        nodeCode: 'validate_node',
        nodeName: '数据验证节点',
        status: 'SUCCESS',
        startTime: '2024-01-01 10:00:01',
        endTime: '2024-01-01 10:00:03',
        duration: 2000
      },
      {
        nodeId: 'node_003',
        nodeCode: 'process_node',
        nodeName: '业务处理节点',
        status: 'RUNNING',
        startTime: '2024-01-01 10:00:03',
        endTime: null,
        duration: null
      }
    ]
  }
  
  detailDialogVisible.value = true
}

/**
 * 查看日志
 */
const viewLogs = async (row) => {
  currentExecution.value = row
  await refreshLogs()
  logDialogVisible.value = true
  
  // 开启自动刷新
  if (autoRefreshLogs.value && row.status === 'RUNNING') {
    startLogRefresh()
  }
}

/**
 * 刷新日志
 */
const refreshLogs = async () => {
  if (!currentExecution.value) return
  
  try {
    // TODO: 调用API获取执行日志
    // const response = await executionApi.getExecutionLogs(currentExecution.value.id)
    
    // 模拟数据
    const newLogs = [
      {
        timestamp: '2024-01-01 10:00:00.123',
        level: 'INFO',
        message: '流程开始执行'
      },
      {
        timestamp: '2024-01-01 10:00:01.456',
        level: 'INFO',
        message: '开始节点执行完成'
      },
      {
        timestamp: '2024-01-01 10:00:02.789',
        level: 'DEBUG',
        message: '数据验证节点开始执行'
      },
      {
        timestamp: '2024-01-01 10:00:03.012',
        level: 'INFO',
        message: '数据验证通过'
      },
      {
        timestamp: '2024-01-01 10:00:03.345',
        level: 'INFO',
        message: '业务处理节点开始执行'
      }
    ]
    
    executionLogs.value = newLogs
    
    // 滚动到底部
    await nextTick()
    if (logViewer.value) {
      logViewer.value.scrollTop = logViewer.value.scrollHeight
    }
    
  } catch (error) {
    ElMessage.error('加载日志失败：' + error.message)
  }
}

/**
 * 清空日志
 */
const clearLogs = () => {
  executionLogs.value = []
}

/**
 * 开始日志自动刷新
 */
const startLogRefresh = () => {
  if (logRefreshTimer) {
    clearInterval(logRefreshTimer)
  }
  logRefreshTimer = setInterval(refreshLogs, 2000)
}

/**
 * 停止日志自动刷新
 */
const stopLogRefresh = () => {
  if (logRefreshTimer) {
    clearInterval(logRefreshTimer)
    logRefreshTimer = null
  }
}

/**
 * 停止执行
 */
const stopExecution = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要停止执行"${row.flowName}"吗？`,
      '确认停止',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await stopExecutionApi(row.id)
    
    row.status = 'STOPPED'
    ElMessage.success('停止成功')
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('停止失败：' + error.message)
    }
  }
}

/**
 * 恢复执行
 */
const resumeExecution = async (row) => {
  try {
    await resumeExecutionApi(row.id)
    
    row.status = 'RUNNING'
    ElMessage.success('恢复成功')
    
  } catch (error) {
    ElMessage.error('恢复失败：' + error.message)
  }
}

/**
 * 重试执行
 */
const retryExecution = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要重新执行"${row.flowName}"吗？`,
      '确认重试',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await retryExecutionApi(row.id)
    
    ElMessage.success('重试成功')
    loadExecutionList()
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('重试失败：' + error.message)
    }
  }
}

/**
 * 执行流程
 */
const executeFlow = () => {
  executeDialogVisible.value = true
}

/**
 * 提交执行
 */
const submitExecution = async () => {
  if (!executeForm.flowCode) {
    ElMessage.warning('请选择要执行的流程')
    return
  }
  
  let inputData = {}
  if (executeForm.inputData.trim()) {
    try {
      inputData = JSON.parse(executeForm.inputData)
    } catch (error) {
      ElMessage.error('输入参数格式错误，请输入有效的JSON')
      return
    }
  }
  
  executing.value = true
  try {
    const executionData = {
      flowCode: executeForm.flowCode,
      inputData
    }
    
    let response
    if (executeForm.async) {
      response = await executeFlowAsync(executionData)
    } else {
      response = await executeFlowSync(executionData)
    }
    
    ElMessage.success('流程执行成功')
    executeDialogVisible.value = false
    loadExecutionList()
    loadStats()
    
  } catch (error) {
    ElMessage.error('执行失败：' + error.message)
  } finally {
    executing.value = false
  }
}

// 生命周期
onMounted(() => {
  loadStats()
  loadExecutionList()
  loadAvailableFlows()
  
  // 开启定时刷新 - 已禁用自动刷新
  // refreshTimer = setInterval(() => {
  //   loadStats()
  //   loadExecutionList()
  // }, 30000) // 30秒刷新一次
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
  stopLogRefresh()
})

// 监听自动刷新日志开关
watch(autoRefreshLogs, (newVal) => {
  if (newVal && currentExecution.value?.status === 'RUNNING') {
    startLogRefresh()
  } else {
    stopLogRefresh()
  }
})

// 监听日志对话框关闭
watch(logDialogVisible, (newVal) => {
  if (!newVal) {
    stopLogRefresh()
  }
})
</script>

<style scoped>
.execution-monitor {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.stats-section {
  margin-bottom: 20px;
}

.stats-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stats-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 10px;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.stats-icon.running {
  background: linear-gradient(135deg, #409eff, #66b1ff);
}

.stats-icon.success {
  background: linear-gradient(135deg, #67c23a, #85ce61);
}

.stats-icon.failed {
  background: linear-gradient(135deg, #f56c6c, #f78989);
}

.stats-icon.total {
  background: linear-gradient(135deg, #909399, #b1b3b8);
}

.stats-info {
  flex: 1;
}

.stats-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  margin-top: 20px;
  text-align: right;
}

.text-muted {
  color: #909399;
}

.detail-content {
  padding: 10px 0;
}

.execution-flow {
  margin-top: 30px;
}

.execution-flow h4 {
  margin-bottom: 20px;
  color: #303133;
}

.node-info {
  padding: 10px 0;
}

.node-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.node-name {
  font-weight: bold;
  color: #303133;
}

.node-details p {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.log-content {
  height: 500px;
  display: flex;
  flex-direction: column;
}

.log-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.log-viewer {
  flex: 1;
  background: #1e1e1e;
  color: #d4d4d4;
  padding: 15px;
  border-radius: 4px;
  overflow-y: auto;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.5;
}

.log-viewer pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-all;
}

.log-info {
  color: #4fc3f7;
}

.log-debug {
  color: #9e9e9e;
}

.log-warn {
  color: #ffb74d;
}

.log-error {
  color: #f44336;
}

.dialog-footer {
  text-align: right;
}

/* 操作按钮容器样式 */
.action-buttons-container {
  display: flex;
  flex-wrap: wrap;
  gap: 6px 8px;
  align-items: center;
  justify-content: flex-start;
  line-height: 1.2;
}

/* 操作按钮样式优化 */
:deep(.el-button--small) {
  padding: 5px 12px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
  margin: 0;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #409eff, #3a8ee6);
  border: none;
}

:deep(.el-button--success) {
  background: linear-gradient(135deg, #67c23a, #5daf34);
  border: none;
}

:deep(.el-button--danger) {
  background: linear-gradient(135deg, #f56c6c, #f25c5c);
  border: none;
}

:deep(.el-button--warning) {
  background: linear-gradient(135deg, #e6a23c, #d19e2a);
  border: none;
}
</style>